﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Business.EntityFrameworkCore;
using mozhi.smarterp.Business.Products;
using mozhi.smarterp.Business.Products.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Business.Repositories.Product
{
    public class ProductSaleSettingRepository : EfCoreRepository<BusinessDbContext, ProductSaleSetting, Guid>, IProductSaleSettingRepository
    {
        public ProductSaleSettingRepository(IDbContextProvider<BusinessDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<ProductSaleSetting> GetByProductIdAsync(Guid productId)
        {
            var dbContext = await GetDbContextAsync();

            var saleSetting = await dbContext.Set<ProductSaleSetting>().AsNoTracking().FirstOrDefaultAsync(x=>x.ProductId == productId);

            return saleSetting;
        }

        public async Task<int> GetCountAsync(Guid? productId, Guid? excludeId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<ProductSaleSetting>().AsNoTracking()
                .WhereIf(productId.HasValue , x=>x.ProductId == productId)
                .WhereIf(excludeId.HasValue , x=>x.Id!=excludeId)
                .CountAsync();

            return count;
        }

        public async Task<List<ProductSaleSetting>> GetListAsync(List<Guid> productIds, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var saleSettings = await dbContext.Set<ProductSaleSetting>().AsNoTracking()
                .Where(x => productIds.Contains(x.ProductId))
                .ToListAsync();

            return saleSettings;
        }
    }
}
